package com.demo.topics;

import java.util.Locale;

import android.accounts.AccountManager;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.demo.topics.util.SessionManager;

public class MainActivity extends FragmentActivity implements
		ActionBar.TabListener, SessionManager.SessionListener {
    private final String TAG = MainActivity.class.getSimpleName();

    // UI elements
    private PlaylistFragment mPlaylistFragment;
    private SearchFragment mSearchFragment;

    private MenuItem mLoginMenuItem;
    private MenuItem mLogoutMenuItem;

    private SessionManager mSessionManager;

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

        // Set up the session manager
        mSessionManager = SessionManager.getInstance(this);
        mSessionManager.addSessionListener(this);

		// Set up the action bar.
		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Instantiate the fragments
        mPlaylistFragment = new PlaylistFragment();
        mSearchFragment = new SearchFragment();

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(
				getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		// When swiping between different sections, select the corresponding
		// tab. We can also use ActionBar.Tab#select() to do this if we have
		// a reference to the Tab.
		mViewPager
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						actionBar.setSelectedNavigationItem(position);
					}
				});

		// For each of the sections in the app, add a tab to the action bar.
		for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
			// Create a tab with text corresponding to the page title defined by
			// the adapter. Also specify this Activity object, which implements
			// the TabListener interface, as the callback (listener) for when
			// this tab is selected.
			actionBar.addTab(actionBar.newTab()
					.setText(mSectionsPagerAdapter.getPageTitle(i))
					.setTabListener(this));
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
        mLoginMenuItem = menu.findItem(R.id.action_login);
        mLogoutMenuItem = menu.findItem(R.id.action_logout);

        // TODO update this menu in real time depending on the session status
        if(mSessionManager.isUserLoggedIn()) {
            mLoginMenuItem.setVisible(false);
            mLogoutMenuItem.setVisible(true);
        } else {
            mLogoutMenuItem.setVisible(false);
            mLoginMenuItem.setVisible(true);
        }

		return true;
	}

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.action_logout:
                logout();
                break;
            case R.id.action_login:
                mSessionManager.startAuthFlow();
                break;
        }
        return true;
    }

    private void logout() {
        Log.d(TAG, "Logging out");
        mPlaylistFragment.logoutAndClearPlaylists();
        // TODO notify the other view to swap layouts
    }

    @Override
	public void onTabSelected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
		// When the given tab is selected, switch to the corresponding page in
		// the ViewPager.
		mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "onActivityResult: " + requestCode);
        switch (requestCode) {
            // This is executed when we've selected an account. Let's attempt to
            // authenticate
            case SessionManager.REQUEST_PICK_ACCOUNT:
                if (resultCode == Activity.RESULT_OK) {
                    // Try to authenticate. Get the name
                    String accountName = data
                            .getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                    fetchAuthToken(accountName);
                } else {
                    Log.w(TAG, "Couldn't pick a valid account.");
                }
                break;

            case SessionManager.REQUEST_USER_AUTHORIZATION:
                // While this code looks identical to the result for pick account,
                // it's actually quite different. In the RESULT_OK case, the user
                // has granted access, so we should transparently try to recover
                // from the error and just fetch a new access token. However, in the
                // error case, we may want to recover from this error differently
                // than we would from the error case when we ask the user to select
                // an account.
                if (resultCode == Activity.RESULT_OK) {
                    // This represents the case where the user has authorized our
                    // application. Re-fire off the background task to fetch the
                    // authentication token
                    String accountName = data
                            .getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                    fetchAuthToken(accountName);
                } else {
                    Log.w(TAG, "User did not or could not grant authorization.");
                }
                break;
        }
    }

    /**
     * Punts to the {@link SessionManager} to fetch an auth token and invoke a callback to update the
     * {@link PlaylistFragment} once we have one.
     *
     * @param accountName the account name to fetch an auth token for
     */
    private void fetchAuthToken(String accountName) {
        mSessionManager.fetchAuthToken(accountName);
    }

    @Override
    public void onLoggedIn(String accountName, String authToken) {
        mLogoutMenuItem.setVisible(true);
        mLoginMenuItem.setVisible(false);
    }

    @Override
    public void onLoggedOut() {
        mLogoutMenuItem.setVisible(false);
        mLoginMenuItem.setVisible(true);
    }


    /**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			switch (position) {
			case 0:
				return mSearchFragment;
			case 1:
				return mPlaylistFragment;
			}
			return null; // Shouldn't ever get here
		}

		@Override
		public int getCount() {
			return 2;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			Locale l = Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.title_section1).toUpperCase(l);
			case 1:
				return getString(R.string.title_section2).toUpperCase(l);
			}
			return null;
		}
	}
}
